package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.redp.bizimpl.enums.BizOprEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.enums.ValidatMethodEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.*;
import cc.rengu.redp.bizimpl.upmp.domain.ManagerInfo;
import cc.rengu.redp.bizimpl.upmp.dao.ManagerInfoMapper;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.*;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.SortUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 刘玉亮.LL
 */
@Service
public class ManagerInfoServiceImpl extends ServiceImpl<ManagerInfoMapper, ManagerInfo> implements IManagerInfoService {

    @Autowired
    private IUpmpOrganizationService organizationsService;

    @Autowired
    private IAgentInfoService agentInfoService;

    @Autowired
    private IUpmpPrivilegeCheckService upmpPrivilegeCheckService;
    @Autowired
    private RegionInfoService regionInfoService;
    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    @Autowired
    private IBizTmpService bizTmpService;
    @Autowired
    private IBizHisService bizHisService;
    @Autowired
    private IUpmpSysSeqService upmpSysSeqService;
    @Override
    public IPage<ManagerInfo> findByPage(QueryRequest request, ManagerInfo info) {
        try {
            LambdaQueryWrapper<ManagerInfo> queryWrapper = new LambdaQueryWrapper<>();
            // 当前登录用户
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            String instId = info.getInstId();
            if (null != user && user.isAdmin()) {
                if (StringUtils.isNotBlank(instId)) {
                    instId = user.getInstId();
                    queryWrapper.eq(ManagerInfo::getInstId, info.getInstId());
                }
            } else {
                instId = user.getInstId();
//                queryWrapper.in(ManagerInfo::getCrtOrgId,  GZIPUtils.uncompressToString(user.getUserOrgCodes());
                queryWrapper.eq(ManagerInfo::getInstId, instId);
            }
            if (StringUtils.isNotBlank(info.getRoleType())) {
                queryWrapper.likeRight(ManagerInfo::getRoleType, info.getRoleType());
            }
            if (StringUtils.isNotBlank(info.getManagerName())) {
                queryWrapper.like(ManagerInfo::getManagerName, info.getManagerName());
            }
            if (StringUtils.isNotBlank(info.getManagerPhone())) {
                queryWrapper.like(ManagerInfo::getManagerPhone, info.getManagerPhone());
            }
            if (StringUtils.isNotBlank(info.getManagerId())) {
                queryWrapper.like(ManagerInfo::getManagerId, info.getManagerId());
            }
            if (StringUtils.isNotBlank(info.getUserStatus())) {
                queryWrapper.like(ManagerInfo::getUserStatus, info.getUserStatus());
            }
            if (StringUtils.isNotBlank(info.getSignInstIdOrg())) {
                queryWrapper.like(ManagerInfo::getSignInstId, info.getSignInstIdOrg());
            }
            if (StringUtils.isNotBlank(info.getSignInstIdAgent())) {
                queryWrapper.like(ManagerInfo::getSignInstId, info.getSignInstIdAgent());
            }
            if (StringUtils.isNotBlank(info.getSignInstType())) {
                queryWrapper.like(ManagerInfo::getSignInstType, info.getSignInstType());
            }
            Page<ManagerInfo> page = new Page<>();
            SortUtil.handlePageSort(request, page, true);
            Page<ManagerInfo> page1 = this.page(page, queryWrapper);
            for (ManagerInfo m : page1.getRecords()) {
           /* m.setOptType("修改");
            if(m.getBatchNo()!=null){
                m.setOptType("导入");
            }
            if(!m.getOpenId().equals("OPENID")){
                m.setOptType("认证");
            }*/
                if ("BANK".equals(m.getSignInstType())) {
                    UpmpOrganization organization = organizationsService.getOrgByCode(m.getSignInstId(), instId);
                    if (Common.isNotBlank(organization)) {
                        m.setRemark1(organization.getOrgName());
                    }
                } else if ("AGENT".equals(m.getSignInstType())) {
                    AgentInfo agentInfo = agentInfoService.findOneByAgentCode(m.getSignInstId(), instId);
                    if (Common.isNotBlank(agentInfo)) {
                        m.setRemark1(agentInfo.getAgentName());
                    }
                }
                if(Common.isNotBlank(m.getArea())){
                    RegionInfo regionInfo = regionInfoService.findOneByCode(m.getArea());
                    if (Common.isNotBlank(regionInfo)) {
                        m.setRemark2(regionInfo.getRegionName());
                    }
                }
            }
            return page1;
        } catch (Exception e) {
            log.error("查询失败", e);
            return null;
        }
    }

    @Override
    public List<ManagerInfo> findManagerInfoByManagerId(String managerId) {
        LambdaQueryWrapper<ManagerInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ManagerInfo::getManagerId, managerId);
        return this.list(queryWrapper);
    }

    @Override
    public List<ManagerInfo> findManagerInfoByManagerPhone(String managerPhone, String instId) {
        LambdaQueryWrapper<ManagerInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ManagerInfo::getManagerPhone, managerPhone);
        queryWrapper.eq(ManagerInfo::getInstId, instId);
        return this.list(queryWrapper);
    }

    @Override
    public List<ManagerInfo> getManagerInfoBySignInstId(String signinstid, String instId) {
        LambdaQueryWrapper<ManagerInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ManagerInfo::getInstId, instId);
        queryWrapper.eq(ManagerInfo::getSignInstId, signinstid);
        return this.list(queryWrapper);
    }

    @Override
    public OperationResult saveData(String oprMenuId, String oprMenuName, ManagerInfo entity, HttpServletRequest request, String webNextUrl) throws RedpException {
        String flag = request.getParameter("optFlag");
        Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String instId = entity.getInstId();
        String crtOrgId = "";

        if (flag.equals("add") && user.isAdmin()) {
            if (StringUtils.isEmpty(instId)) {
                log.error("保存数据时请先选择法人行!");
                return OperationResult.buildFailureResult("保存数据时请先选择法人行!");
            } else {
                UpmpOrganization headOrg = organizationsService.getHeadOrgByCode(instId);
                crtOrgId = (headOrg == null ? user.getOrgCode() : headOrg.getOrgCode());
            }
        } else {
            instId = (instId == null ? user.getInstId() : instId);
            crtOrgId = (entity.getCrtOrgId() == null ? user.getOrgCode() : entity.getCrtOrgId());
        }
        UpmpOrganization org = organizationsService.getOrgByCode(crtOrgId, instId);
        ManagerInfo oldEntity = null;
        if (!PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(flag)) {
            oldEntity = this.getById(entity.getId());
        }

        if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(flag)) {
            //UpmpPrivilegeCheck privilegeCheck = upmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "商户管理:拓展经理:增加");

            entity.setId(null);
            entity.setOprId(user.getId());
            entity.setCreateTime(lastUpddt);
            entity.setOpenId("OPENID");
            entity.setCrtOrgId(user.getOrgCode());
            //
            this.save(entity);

            bizHisService.saveBizHisNew(entity, entity, user, org.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt
                    , oprMenuId, oprMenuName, String.valueOf(entity.getId()), null, null, null);
            result.put("id", entity.getId());
        } else if (PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(flag)) {
            String id = request.getParameter("id");
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                return OperationResult.buildFailureResult("请求参数(id)异常!", result);
            }

            //UpmpPrivilegeCheck privilegeCheck = upmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "商户管理:拓展经理:修改");
            this.saveOrUpdate(entity);

            bizHisService.saveBizHisNew(entity, oldEntity, user, org.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt
                    , oprMenuId, oprMenuName, String.valueOf(entity.getId()), null, null, null);
            result.put("id", entity.getId());
        } else if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(flag)
                || PageOptFlagEnum.OPT_FLAG_USE.getType().equals(flag)
                || PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(flag)) {
            String id = request.getParameter("id");
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                return OperationResult.buildFailureResult("请求参数(id)异常!", result);
            }
            ManagerInfo managerInfo = this.getById(id);

            if (Common.isBlank(managerInfo)) {
                log.error("根据id没有找到指定数据！");
                return OperationResult.buildFailureResult("根据id没有找到指定数据！", result);
            }
            UpmpPrivilegeCheck privilegeCheck = new UpmpPrivilegeCheck();
            String bizOpr = "";
            if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(flag)) {
                bizOpr = BizOprEnum.OPR_STOP.getType();
//                privilegeCheck = upmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "商户管理:拓展经理:停用");
//                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
//                } else {
//                }
            } else if (PageOptFlagEnum.OPT_FLAG_USE.getType().equals(flag)) {
                bizOpr = BizOprEnum.OPR_USE.getType();
//                privilegeCheck = upmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "商户管理:拓展经理:启用");
//                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
//                } else {
//                }
            } else if (PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(flag)) {

                managerInfo.setUserStatus("01");

                bizOpr = BizOprEnum.OPR_CANCEL.getType();
//                privilegeCheck = upmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "商户管理:拓展经理:注销");
//                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
//                } else {
//                }
            }
            managerInfo.setLastOprId(user.getId());
            managerInfo.setLastUpdateTime(lastUpddt);
            this.saveOrUpdate(managerInfo);

            bizHisService.saveBizHisNew(managerInfo, oldEntity, user, org.getInstId(), bizOpr, lastUpddt
                    , oprMenuId, oprMenuName, String.valueOf(managerInfo.getId()), null, null, null);
        } else if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(flag)) {

            String id = request.getParameter("id");
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                return OperationResult.buildFailureResult("请求参数(id)异常!", result);
            }

            //获取临时表数据并转换成实体对象
            BizTmp tmp = bizTmpService.getById(id);
            if (Common.isBlank(tmp)) {
                log.error("根据id没有找到指定临时表数据！");
                return OperationResult.buildFailureResult("根据id没有找到指定临时表数据！", result);
            }
            String bizdata = "";
            if (null != tmp.getBizData1()) {
                bizdata += tmp.getBizData1();
            }
            if (null != tmp.getBizData2()) {
                bizdata += tmp.getBizData2();
            }
            if (null != tmp.getBizData3()) {
                bizdata += tmp.getBizData3();
            }
            ManagerInfo managerInfoNew = JSON.parseObject(bizdata, ManagerInfo.class);

            ManagerInfo managerInfo = this.getById(id);
            if (Common.isBlank(managerInfo) && !BizOprEnum.OPR_ADD.equals(tmp.getBizOpr())) {
                log.error("根据id没有找到指定数据！");
                return OperationResult.buildFailureResult("根据id没有找到指定数据！", result);
            }

            String opt = request.getParameter("opt");
            if (Common.isBlank(opt)) {
                log.error("请求参数(opt)异常!");
                return OperationResult.buildFailureResult("请求参数(opt)异常!", result);
            }

            String bizOpr = "";
            BeanUtils.copyProperties(managerInfoNew, managerInfo);
            String approvalRefuseReason = request.getParameter("approvalRefuseReason");

        }

        return OperationResult.buildSuccessResult("数据保存处理完成", result);
    }

    //从Excel读取对象
    @Override
    public List<ManagerInfo> getManagerInfoFromXls(String filePath, int maxRecords, Map<String, String> result) throws IOException, RedpException {
        List<ManagerInfo> list = new ArrayList<ManagerInfo>();
        StringBuffer erroBf = new StringBuffer();
        int realRows =  0;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(filePath);
            if (filePath.endsWith(".xls")) {
                HSSFWorkbook workbook = new HSSFWorkbook(fis); // 2003版本的excel，用.xls结尾.得到工作簿
                HSSFSheet sheet = workbook.getSheetAt(0);
                Row row;
                realRows =  CommonUtils.findRealRows(sheet);
                if(maxRecords<realRows){
                    log.error("导入文件中拓展经理信息记录数超过"+maxRecords+"！");
                    throw new RedpException("导入文件中拓展经理信息记录数超过"+maxRecords+"！");
                }
                // 把第一行跳过
                for (int i = 1; i <= realRows; i++) {
                    row = sheet.getRow(i);
                    ManagerInfo managerInfo = row2ManagerInfo(row, erroBf, i + 1);
                    //生成ManagerInfo ，加入list
                    list.add(managerInfo);
                }
                if (list.size() > 0) {
                    result.put("uploadErrMsg", erroBf.toString());
                    return list;
                } else {
                    result.put("uploadErrMsg", "上传文件无数据。");
                    return null;
                }
            } else if (filePath.endsWith(".xlsx")) {
                XSSFWorkbook workbook = new XSSFWorkbook(fis);
                XSSFSheet sheet = workbook.getSheetAt(0);
                Row row;
                realRows =  CommonUtils.findRealRows(sheet);
                if(maxRecords<realRows){
                    log.error("导入文件中拓展经理信息记录数超过{"+maxRecords+"}！");
                    throw new RedpException("导入文件中拓展经理信息记录数超过"+maxRecords+"！");
                }
                // 把第一行跳过
                for (int i = 1; i <= realRows; i++) {
                    row = sheet.getRow(i);
                    ManagerInfo managerInfo = row2ManagerInfo(row, erroBf, i + 1);
                    //生成ManagerInfo ，加入list
                    list.add(managerInfo);
                }
                if (list.size() > 0) {
                    result.put("uploadErrMsg", erroBf.toString());
                    return list;
                } else {
                    result.put("uploadErrMsg", "上传文件无数据。");
                    return null;
                }
            }else{
                result.put("uploadErrMsg", "上传文件格式不正确。");
                return null;
            }

        } catch (FileNotFoundException e) {
            log.error(e.getMessage());
            return null;
        } catch (IOException e){
            log.error(e.getMessage());
            return null;
        } finally {
            if(null != fis){
                fis.close();
            }
        }
    }
    private String getCellValue(Row row,int cellNum) {
        Cell cell = row.getCell(cellNum);
        if(cell == null){
            return null;
        }
        cell.setCellType(Cell.CELL_TYPE_STRING);
        return cell.getStringCellValue();
    }

    private ManagerInfo row2ManagerInfo(Row row, StringBuffer result,int n){
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String uploadErrMsg = "";
        ManagerInfo managerInfo = new ManagerInfo();
        String managerId = getCellValue(row,0);
        if (StringUtils.isNotBlank(managerId)){
            List<ManagerInfo> mIdList = this.findManagerInfoByManagerId(managerId);
            if (null != mIdList && mIdList.size() > 0) {
                uploadErrMsg += "员工号已存在，不能重复；";
            }else{
                managerInfo.setManagerId(managerId);
            }
        } else {
            uploadErrMsg += "员工号不能为空；";
        }
        String managerName = getCellValue(row,1);
        if (StringUtils.isNotBlank(managerName)){
            managerInfo.setManagerName(managerName);
        } else {
            uploadErrMsg += "姓名不能为空；";
        }
        String managerPhone = getCellValue(row,2);
        if (StringUtils.isNotBlank(managerPhone)){
            String managerPhonevali = StringValicationUtil.validate(ValidatMethodEnum.CHECK_PHONE,managerPhone);
            if (StringUtils.isNotBlank(managerPhonevali)){
                uploadErrMsg += "手机号"+managerPhonevali+"；";
            }else{
                List<ManagerInfo> phoneList = this.findManagerInfoByManagerPhone(managerPhone,user.getInstId());
                if (null != phoneList && phoneList.size() > 0) {
                    uploadErrMsg += "手机号已存在，不能重复；";
                }else{
                    managerInfo.setManagerPhone(managerPhone);
                }
            }
        } else {
            uploadErrMsg += "手机号不能为空；";
        }
        String roleType = getCellValue(row,3);
        if (StringUtils.isNotBlank(roleType)){
            roleType = roleType.substring(0,roleType.indexOf("-"));
            managerInfo.setRoleType(roleType);
        } else {
            uploadErrMsg += "拓展经理角色不能为空；";
        }
        String signInstType = getCellValue(row,4);
        if (StringUtils.isNotBlank(signInstType)){
            signInstType = signInstType.substring(0,signInstType.indexOf("-"));
            managerInfo.setSignInstType(signInstType);
        } else {
            uploadErrMsg += "收单机构类型不能为空；";
        }
        String signInstId = getCellValue(row,5);
        if (StringUtils.isNotBlank(signInstId)){
            String instId = user.getInstId();
            String userOrgCodes = "";
//            String userOrgCodes = GZIPUtils.uncompressToString(user.getUserOrgCodes());
            UpmpOrganization org = null;
            AgentInfo agentInfo = null;
            if("BANK".equals(signInstType)){
                if(!StringUtils.isBlank(userOrgCodes) && userOrgCodes.contains(signInstId)){
                    org  = organizationsService.getOrgByCode(signInstId, instId);
                }
            }else if("AGENT".equals(signInstType)){
                if(!StringUtils.isBlank(userOrgCodes)){
                    String[] orgs = userOrgCodes.split(",");
                    List<String> orgList = Arrays.asList(orgs);
                    agentInfo = agentInfoService.findOneByCodeAndCrtOrg(signInstId, BusinessContainer.impStatus_01,orgList);
                }
            }
            if(Common.isBlank(org) && Common.isBlank(agentInfo)){
                uploadErrMsg += "收单机构代码不存在；";
            }else{
                managerInfo.setSignInstId(signInstId);
            }
        } else {
            uploadErrMsg += "收单机构代码不能为空；";
        }
        String province = getCellValue(row,6);
        if (StringUtils.isNotBlank(province)){
            RegionInfo regionInfo = regionInfoService.findOneByCode(province, BusinessContainer.data_sta_01);
            if(Common.isBlank(regionInfo)){
                uploadErrMsg += "地区代码-省不存在；";
            }else{
                managerInfo.setProvince(province);
            }
        }
        String city = getCellValue(row,7);
        if (StringUtils.isNotBlank(city)){
            RegionInfo regionInfo = regionInfoService.findByUkAndStatusAndPtCode(city,BusinessContainer.data_sta_01,province);
            if(Common.isBlank(regionInfo)){
                uploadErrMsg += "地区代码-市不存在；";
            }else {
                managerInfo.setCity(city);
            }
        }
        String area = getCellValue(row,8);
        if (StringUtils.isNotBlank(area)){
            RegionInfo regionInfo = regionInfoService.findByUkAndStatusAndPtCode(area,BusinessContainer.data_sta_01,city);
            if(Common.isBlank(regionInfo)){
                uploadErrMsg += "地区代码-区不存在；";
            }else {
                managerInfo.setArea(area);
            }
        }

        if (!"".equals(uploadErrMsg)){
            uploadErrMsg = "第"+n+"行：" + uploadErrMsg + "</br>";
            result.append(uploadErrMsg);
        }

        return managerInfo;
    }
    @Override
    //批量验证保存
    public Map<String,String> batchSave(String oprMenuId, String oprMenuName, List<ManagerInfo> list, HttpServletRequest request, String webNextUrl) throws RedpException {
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        ManagerInfo entity=list.get(0);
        String instId=entity.getInstId();
        String crtOrgId = "";
        if(user.isAdmin()){
            if(StringUtils.isEmpty(instId)){
                log.error("保存数据时请先选择法人行!");
                return resuleBuild(0,"批量保存失败",list.size()+"");
            }else{
                UpmpOrganization headOrg=organizationsService.getHeadOrgByCode(instId);
                crtOrgId=(headOrg==null?user.getOrgCode():headOrg.getOrgCode());
            }
        }else{
            instId=(instId==null?user.getInstId():instId);
            crtOrgId=(entity.getCrtOrgId()==null?user.getOrgCode():entity.getCrtOrgId());
        }
        UpmpOrganization org = organizationsService.getOrgByCode(crtOrgId, instId);
        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        //验证list内是否有重复 手机号 工号
        Set<String> phone = new HashSet<String>();
        Set<String> mId = new HashSet<String>();
        for (ManagerInfo m : list) {
            if (!phone.add(m.getManagerPhone())){
                return resuleBuild(-1,"导入表格中手机号重复"+m.getManagerPhone(),m.getManagerPhone());
            }
            if (!mId.add(m.getManagerId())){
                return resuleBuild(-2,"导入表格中工号重复"+m.getManagerId(),m.getManagerId());
            }
        }

        //验证手机号 工号 是否已存在
        /*for (int i = 0; i < list.size(); i++) {
            ManagerInfo m = list.get(i);
            List<ManagerInfo> phoneList = findManagerInfoByManagerPhone(m.getManagerPhone());
            if(phoneList!=null && phoneList.size()>0){
                int n = i+1;
                String msg = "第"+n+"行，";
                return resuleBuild(-3,msg+"手机号已存在",m.getManagerPhone());
            }

            List<ManagerInfo> mIdList = findManagerInfoByManagerId(m.getManagerId());
            if (mIdList!=null && mIdList.size()>0){
                int n = i+1;
                String msg = "第"+n+"行，";
                return resuleBuild(-4,msg+"工号已存在",m.getManagerId());
            }

            if (org==null) {
                int n = i+1;
                String msg = "第"+n+"行，";
                return resuleBuild(-5,msg+"收单机构不存在",m.getSignInstId());
            }
        }*/

        for (ManagerInfo m : list) {
            //补充数据
            fillManagerInfo(m);
           this.saveOrUpdate(m);
            bizHisService.saveBizHisNew(m,m,user,org.getInstId(),BizOprEnum.OPR_ADD.getType(),lastUpddt,oprMenuId,oprMenuName,m.getId(),null,null,null);
        }

        return resuleBuild(1,"批量保存成功",list.size()+"");
    }

    private void fillManagerInfo(ManagerInfo entity){
        UpmpUserInfoVO user =CommonUtils.getCurrentUser(upmpSysParamService);
        SimpleDateFormat fmtdt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String lastUpddt = fmtdt.format(new Date());
        entity.setId(null);
        entity.setOprId(user.getId());
        entity.setCreateTime(lastUpddt);
        entity.setCrtOrgId(user.getOrgCode());
        entity.setOpenId("OPENID");
        entity.setBatchNo(generateCode("0"));
        entity.setUserStatus("00");
        entity.setLastOprId(user.getId());
        entity.setLastUpdateTime(lastUpddt);
    }
    /**
     * 系统自动生成代理商编码：AG + 8位顺序编码
     *
     * @return
     */
    public String generateCode(String instId) {
        // 获取渠道ID：固定20
        String channelId = CommonUtils.getChannelId(upmpSysParamService,instId);
        // 代理商编码前缀：AG
        String prefix = BusinessContainer.MANAGER_BATCH;
        // 自动生成一级代码
        String paramCode = BusinessContainer.COMM_PARAM_CODE;
        // 生成序列号
        String seqNum =  upmpSysSeqService.updateParamValue(paramCode, "Manager_Batch_CD", channelId);

        // 代理商编码
        String result = prefix + String.format("%08d", Integer.parseInt(seqNum));
        return result;
    }
    private Map<String,String> resuleBuild(int code, String msg, String value){
        Map<String, String> resule = new HashMap<String, String>();
        if (code > 0) {
            resule.put("status","success");
        } else {
            resule.put("status","error");
        }
        resule.put("code",code+"");
        resule.put("msg",msg);
        resule.put("value",value);
        return resule;
    }
    @Override
    public List<Map> exportList(HttpServletRequest request) {
        UpmpUserInfoVO user =CommonUtils.getCurrentUser(upmpSysParamService);
        String instId = "";
        String orgCodes = "";
        if (null != user && user.isAdmin()) {
            instId = request.getParameter("instId");
        } else if(null != user){
            instId = user.getInstId();
//            String userOrgCodes = GZIPUtils.uncompressToString(user.getUserOrgCodes());
            String userOrgCodes = "";
            orgCodes = userOrgCodes.replaceAll(",", "','");
            orgCodes = "'" + orgCodes + "'";
        }
        String roleType = request.getParameter("roleType");
        String managerName = request.getParameter("managerName");
        String managerPhone = request.getParameter("managerPhone");
        String managerId = request.getParameter("managerId");
        String signInstId = request.getParameter("signInstId");
        String userStatus = request.getParameter("userStatus");
        String signInstType = request.getParameter("signInstType");

        HashMap<String, Object> param = new HashMap<>();
        param.put("instId",instId);
        if(!"".equals(orgCodes)){
            param.put("orgCodes",orgCodes);
        }
        if (StringUtils.isNotBlank(roleType)){
            param.put("roleType",roleType);
        }
        if (StringUtils.isNotBlank(managerName)){
            param.put(":managerName",managerName);
        }
        if (StringUtils.isNotBlank(managerPhone)){
            param.put("managerPhone",managerPhone);
        }
        if (StringUtils.isNotBlank(managerId)){
            param.put("managerId",managerId);
        }
        if (StringUtils.isNotBlank(signInstId)){
            param.put("signInstId",signInstId);
        }
        if (StringUtils.isNotBlank(userStatus)){
            param.put("userStatus",userStatus);
        }
        if (StringUtils.isNotBlank(signInstType)){
            param.put("signInstType",signInstType);
        }
        return this.baseMapper.getExportList(param);
    }
}
